//
//  SEGOtherCreatActivityListViewController.m
//  ExcellentHome
//
//  Created by 陈区 on 13-11-22.
//  Copyright (c) 2013年 陈区. All rights reserved.
//
#import "ActivityTypeCell.h"
#import "ActivityListCell.h"
#import "ActivityRequestModel.h"

#import "SEGOtherCreatActivityListViewController.h"
#import "SEGOtherCreateActivityDetailViewController.h"
#import "SEGActivityTypeViewController.h"
//#import "UIImageView+WebCache.h"
//#import "ActivityModel.h"

@interface SEGOtherCreatActivityListViewController ()

@property (nonatomic, retain)ActivityRequestModel *activityRequestModel;

@end

@implementation SEGOtherCreatActivityListViewController
@synthesize activityType, viewControllerDelegate;
@synthesize jionActivityID;
@synthesize thumbImgView,activityID;
@synthesize chatGroupID;
@synthesize typeArray,typeNameArray;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)setupUI {
    m_tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    m_tableView.delegate = self;
    m_tableView.dataSource = self;
    m_tableView.backgroundView=nil;
    m_tableView.separatorStyle=UITableViewCellSelectionStyleNone;
    m_tableView.backgroundColor = [UIColor whiteColor];
    [m_tableView registerClass:[ActivityListCell class] forCellReuseIdentifier:kActivityListCellIdentifier];
    [m_tableView registerClass:[ActivityTypeCell class] forCellReuseIdentifier:kActivityTypeCellIdentifier];
    
    if(@available(iOS 11.0, *)){
        m_tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        m_tableView.estimatedSectionHeaderHeight  = m_tableView.estimatedSectionHeaderHeight > 0 ? m_tableView.estimatedSectionHeaderHeight : 0;
        m_tableView.estimatedSectionFooterHeight  = m_tableView.estimatedSectionFooterHeight > 0 ? m_tableView.estimatedSectionFooterHeight : 0;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    [self.view addSubview:m_tableView];
    [[SEGUhomeMediator sharedInstance] seg_showCustomProgressImage:@{@"view":self.view}];
    
    [m_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setupUI];
    
    [m_tableView addWindmillWithHeaderRefreshBlock:^{
        isRequestNewNews = YES;
        [self.activityRequestModel requestIsEqualIdNumber:^(id result, NSError *error) {
            [m_tableView stopAnimatingWindmill];
            [self dealWithActivityIdsResult:result];
        }];
    }];
    
    [self showCustomNavigationBackButton];
    self.title = @"活动";
}

-(void)pushNewsDetial:(NSDictionary*)userinfo
{
//    SEGOtherCreateActivityDetailViewController *detailCtl = [[SEGOtherCreateActivityDetailViewController alloc] init];
//    detailCtl.hidesBottomBarWhenPushed = YES;
//    [detailCtl addServiceId:[userinfo objectForKey:@"serviceId"]];
//    [viewControllerDelegate pushViewController:detailCtl];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    
    self.activityType=nil;
    
    [self refreshData];
}

-(void)refreshData{
    
    self.activityType=nil;
    
    [self.activityRequestModel requestIsEqualIdNumber:^(id result, NSError *error) {
        [self dealWithActivityIdsResult:result];
    }];
}

#pragma mark - tableview datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    self.typeArray=[NSMutableArray array];
    self.typeNameArray=[NSMutableArray array];
    if ([recomendArray count]>0) {
        [self.typeNameArray addObject:@"推荐活动"];
        NSDictionary*dic=[NSDictionary dictionaryWithObject:recomendArray forKey:@"推荐活动"];
        [self.typeArray addObject:dic];
    }
    if ([hotArray count]>0) {
        [self.typeNameArray addObject:@"热门活动"];
        NSDictionary*dic=[NSDictionary dictionaryWithObject:hotArray forKey:@"热门活动"];
        [self.typeArray addObject:dic];
    }
    if([objectArray count]>0){
        [self.typeNameArray addObject:@"全部活动"];
        NSDictionary*dic=[NSDictionary dictionaryWithObject:objectArray forKey:@"全部活动"];
        [self.typeArray addObject:dic];
    }
    return [self.typeNameArray count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section;
{
    return 0.1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section;
{
    return 40;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger numberOfRows=[[[self.typeArray objectAtIndex:section] objectForKey:[self.typeNameArray objectAtIndex:section]] count]+1;
    if (numberOfRows>4) {
        return 4;
    }else{
        return numberOfRows;
    }
}
//每行的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row==0) {
        return 40;
        
    }else{
        return 80;
    }
    
}
#pragma mark - tableview delegate
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    NSUInteger rowCount = [[[self.typeArray objectAtIndex:section] objectForKey:[self.typeNameArray objectAtIndex:section]] count];
    
    if (row == 0) {//分类标题
        
        ActivityTypeCell *cell = [ActivityTypeCell cellWithTableView:tableView];
        [cell setTypeName:[self.typeNameArray objectAtIndex:indexPath.section]];
        [cell setTypeCount:rowCount];

        return cell;
        
    }else {
        
        ActivityListCell *cell = [ActivityListCell cellWithTableView:tableView];
        cell.dataSource = [[[self.typeArray objectAtIndex:indexPath.section] objectForKey:[self.typeNameArray objectAtIndex:indexPath.section]]objectAtIndex:row-1];;
        //每个section最后一个活动 线和屏幕等宽
        if (row == rowCount || row == 3) {
            cell.isLastRow = YES;
        }else {
            cell.isLastRow = NO;
        }
        return cell;
        
    }
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.row==0) {
        SEGActivityTypeViewController *TypeView=[[SEGActivityTypeViewController alloc] init];
        TypeView.hidesBottomBarWhenPushed = YES;
        TypeView.typeAry = [[self.typeArray objectAtIndex:indexPath.section] objectForKey:[self.typeNameArray objectAtIndex:indexPath.section]];
        TypeView.naTitle = [self.typeNameArray objectAtIndex:indexPath.section];
        [viewControllerDelegate pushViewController:TypeView];
        
    }else{
        ActivityModel *entity = [[[self.typeArray objectAtIndex:indexPath.section] objectForKey:[self.typeNameArray objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row-1];
        SEGOtherCreateActivityDetailViewController *detailCtl = [[SEGOtherCreateActivityDetailViewController alloc] init];
        detailCtl.hidesBottomBarWhenPushed = YES;
        [detailCtl addActivityData:entity];
        [viewControllerDelegate pushViewController:detailCtl];
    }
}

#pragma mark - 处理网络请求数据
- (void)dealWithActivityIdsResult:(NSDictionary *)resultDict
{
    NSString *code = [resultDict objectForKey:@"code"];
    
    if([[resultDict objectForKey:@"code"] isEqualToString:@"0"])
    {
        NSString *ids = [resultDict objectForKey:@"ids"];
        if (ids && ids.length > 0) {
            [self.activityRequestModel requestActivityModelListWithIds:ids finished:^(id result, NSError *error) {
                [self dealWithActivityListResult:result];
            }];
        }
    }
}

- (void)dealWithActivityListResult:(NSDictionary *)resultDict
{
    
    if (isRequestNewNews)
    {
        isRequestNewNews = NO;
        [m_tableView stopAnimatingWindmill];
    }
    
    if ([resultDict count]==0) {
        return;
    }
    NSString *code = [resultDict objectForKey:@"code"];
    
    if([code isEqualToString:@"0"])
    {
        NSMutableArray *allArr = [NSMutableArray array];
        NSMutableArray *hotArr = [NSMutableArray array];
        NSMutableArray *recomendArr = [NSMutableArray array];
        
        for (NSDictionary *item in [resultDict objectForKey:@"data"]) {
            ActivityModel *model = [ActivityModel initWithDictionary:item];
            if ([[model.status stringValue] isEqualToString:@"2"]) {
                [allArr addObject:model];
                
                if ([[model.top stringValue] isEqualToString:@"2"]) {
                    [hotArr addObject:model];
                }else if ([[model.top stringValue] isEqualToString:@"1"]) {
                    [recomendArr addObject:model];
                }
            }
        }
        
        objectArray = [allArr copy];
        recomendArray = [recomendArr copy];
        hotArray = [hotArr copy];
        

        if([objectArray count] > 0)
        {
            [[SEGUhomeMediator sharedInstance]seg_hideCustomProgressImage:@{@"view":self.view}];
        }
        else
        {
            [[SEGUhomeMediator sharedInstance] seg_showCustomProgressImage:@{@"view":self.view}];
        }
        [m_tableView reloadData];
        
    }
}

#pragma mark - getter
- (ActivityRequestModel *)activityRequestModel
{
    
    if (!_activityRequestModel) {
        
        _activityRequestModel = [[ActivityRequestModel alloc] init];
    }
    
    return _activityRequestModel;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
